package com.panda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panda.annotation.PageView;
import com.panda.annotation.SystemLog;
import com.panda.constants.SystemConstants;
import com.panda.entity.po.Article;
import com.panda.entity.po.Category;
import com.panda.entity.po.User;
import com.panda.entity.po.Video;
import com.panda.entity.vo.ArticleVo;
import com.panda.entity.vo.PageVo;
import com.panda.entity.vo.VideoDetailVo;
import com.panda.entity.vo.VideoVo;
import com.panda.enums.AppHttpCodeEnum;
import com.panda.mapper.VideoMapper;
import com.panda.service.CategoryService;
import com.panda.service.UserService;
import com.panda.service.VideoService;
import com.panda.utils.BeanCopyUtil;
import com.panda.utils.RespondResult;
import com.panda.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.panda.utils.DataFormatUtil.twoDimensionListSort;

/**
 * (Video)表服务实现类
 *
 * @author makejava
 * @since 2022-05-13 15:07:54
 */
@Service("videoService")
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private VideoMapper videoMapper;

    @Override
    @SystemLog(businessName = "上传视频")
    public RespondResult<VideoVo> postVideo(VideoVo videoVo) {
        //判断用户是否登陆
        Long userId;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            return RespondResult.errorResult(AppHttpCodeEnum.ERROR_POST_VIDEO);
        }

        Video video = BeanCopyUtil.copyBean(videoVo, Video.class);
        Category category = categoryService.getById(videoVo.getCategoryId());
        video.setCategoryName(category.getCategoryName());
        video.setCreateBy(userId);
        save(video);
        return RespondResult.okResult(videoVo);
    }

    @Override
    @SystemLog(businessName = "获取所有视频")
    public RespondResult<PageVo<VideoVo>> getAllVideos(Long id, Integer pageNum, Integer pageSize, Long categoryId, String keyword) {

        LambdaQueryWrapper<Video> videoWrapper = new LambdaQueryWrapper<>();
        //根据用户id查询视频
        videoWrapper.eq(Objects.nonNull(id), Video::getCreateBy, id);
        //判断categoryId字段是否有传值，有就加上判断条件，没有就查询所有
        videoWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Video::getCategoryId, categoryId);
        videoWrapper.like(Objects.nonNull(keyword),Video::getTitle,keyword);
        //判断视频是否通过审核
        videoWrapper.eq(!Objects.nonNull(id), Video::getIsAudit, SystemConstants.VIDEO_IS_AUDIT);
        //文章降序
        videoWrapper.orderByDesc(Video::getCreateTime);
        //分页
        Page<Video> videoPage = new Page<>(pageNum, pageSize);

        videoMapper.selectVideoConnectName(videoPage,videoWrapper);

//        page(videoPage, videoWrapper);
        //对象封装成VO
//        System.out.println("=================>"+videoPage.getRecords());
        List<VideoVo> videoVos = BeanCopyUtil.copyBeans(videoPage.getRecords(), VideoVo.class);
//        System.out.println(videoVos);
        //分页处理，返回给前台
        PageVo<VideoVo> pageVo = new PageVo<>(videoVos, videoPage.getTotal());

        return RespondResult.okResult(pageVo);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    @SystemLog(businessName = "详情")
    @PageView(description = "video")
    public RespondResult<VideoDetailVo> getVideoDetail(Long id) {

        Video video = getById(id);
        if (video == null) {
            return RespondResult.errorResult(AppHttpCodeEnum.GET_VIDEO_ERROR);
        }

        //对象封装成VO
        //利用bean拷贝工具，将文章信息装成Vo
        VideoDetailVo videoDetailVo = BeanCopyUtil.copyBean(video, VideoDetailVo.class);
        //查询这篇文章的分类
        Long categoryId = videoDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        User user = userService.getById(video.getCreateBy());
        videoDetailVo.setAvatar(user.getAvatar());
        videoDetailVo.setUsername(user.getUsername());
        if (category != null) {
            //将分类名设置到文章Vo
            videoDetailVo.setCategoryName(category.getCategoryName());
        }
        return RespondResult.okResult(videoDetailVo);
    }

    /**
     * 修改视频，需登陆
     *
     * @param id
     * @param videoVo
     * @return
     */
    @Override
    @SystemLog(businessName = "修改视频")
    public RespondResult<VideoVo> modifyVideo(Long id, VideoVo videoVo) {


        //判断用户是否登陆
        Long userId;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            return RespondResult.errorResult(AppHttpCodeEnum.MODIFY_VIDEO_ERROR);
        }

        //判断是否是文章作者，不可修改他人文章
        if (!Objects.equals(getById(id).getCreateBy(), userId)) {
            return RespondResult.errorResult(AppHttpCodeEnum.NO_AUTH);
        }

        //通过id查询文章
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Video::getId, id);

        //更新
        Video video = BeanCopyUtil.copyBean(videoVo, Video.class);
        //重新审核
        video.setIsAudit("NULL");
        boolean isUpdate = update(video, wrapper);
        if (isUpdate) {
            return RespondResult.okResult(videoVo);
        }
        return RespondResult.errorResult(AppHttpCodeEnum.MODIFY_VIDEO_ERROR);
    }

    @Override
    @SystemLog(businessName = "删除视频")
    public RespondResult deleteVideo(Long id) {
        //判断用户是否登陆
        Long userId;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            return RespondResult.errorResult(AppHttpCodeEnum.DELETE_VIDEO_ERROR);
        }

        Video video = getById(id);

        //判断这篇文章的作者，是否是此次登陆用户，不可删除别人的文章
        if (!Objects.equals(video.getCreateBy(), userId)) {
            return RespondResult.errorResult(AppHttpCodeEnum.NO_AUTH);
        }

        UpdateWrapper<Video> updateWrapper = new UpdateWrapper<>();
        //通过id获取需要删除的文章
        updateWrapper.eq("id", id);
        updateWrapper.set("del_flag", "1");

        boolean update = update(updateWrapper);

        if (update) {
            return RespondResult.okResult("删除视频成功");
        }

        return RespondResult.errorResult(AppHttpCodeEnum.DELETE_VIDEO_ERROR);
    }

    /**
     * 获取热门视频排行
     */
    @Override
    public RespondResult hotVideos(String topic) {
        List<Map<String, String>> mapList = videoMapper.hotVideos(topic);
        if (mapList.size() == 0){
            RespondResult.errorResult(404,"找不到热门视频列表");
        }
        return RespondResult.okResult(mapList);
    }

    /**
     * 统计过去一周内视频的投稿量
     */
    @Override
    public RespondResult createdVideoStatistic() {
        List<Map<String, String>> mapList = videoMapper.createdVideoStatistic();
        List<LinkedList<String>> linkedList = twoDimensionListSort(mapList);
        return RespondResult.okResult(linkedList);
    }

    /**
     * 统计视频各类目数量
     */
    @Override
    public RespondResult categoryStatistic() {
        List<Map<String, String>> mapList = videoMapper.categoryStatistic();
//        List<LinkedList<String>> linkedLists = twoDimensionListSort(mapList);
        return RespondResult.okResult(mapList);
    }

    /**
     * 根绝类目名称参数，返回该类目下过去一周的投稿数量
     */
    @Override
    public RespondResult createdCategoryOfVideoStatistic(String categoryName) {
        List<Map<String, String>> mapList = videoMapper.createdVideoOfCategory(categoryName);
        List<LinkedList<String>> linkedLists = twoDimensionListSort(mapList);
        return RespondResult.okResult(linkedLists);
    }
}

